﻿// Copyright (c) Inossem. All rights reserved.
// Licensed under the LGPL-3.0 license. See LICENSE file in the project root for full license information.
using DWF.Studio.Share.Log;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DWF.Studio.ScriptEngine.Custom
{
    internal static class DebugSerializeTypeHandler
    {
        private static HashSet<Type> _serializeTypeSet = new HashSet<Type>();

        static DebugSerializeTypeHandler()
        {

            try
            {
                _serializeTypeSet.Add(typeof(System.SByte));
                _serializeTypeSet.Add(typeof(System.Byte));
                _serializeTypeSet.Add(typeof(System.Int16));
                _serializeTypeSet.Add(typeof(System.UInt16));
                _serializeTypeSet.Add(typeof(System.Int32));
                _serializeTypeSet.Add(typeof(System.UInt32));
                _serializeTypeSet.Add(typeof(System.Int64));
                _serializeTypeSet.Add(typeof(System.UInt64));
                _serializeTypeSet.Add(typeof(System.Char));
                _serializeTypeSet.Add(typeof(System.Single));
                _serializeTypeSet.Add(typeof(System.Double));
                _serializeTypeSet.Add(typeof(System.Boolean));
                _serializeTypeSet.Add(typeof(System.Decimal));
                _serializeTypeSet.Add(typeof(System.String));
                _serializeTypeSet.Add(typeof(System.TimeSpan));

                var serializeTypes = (NameValueCollection)ConfigurationManager.GetSection("debugSerializeTypes");
                foreach (string key in serializeTypes)
                {
                    var type = Type.GetType(key);
                    if (type != null)
                    {
                        if (!_serializeTypeSet.Contains(type))
                        {
                            _serializeTypeSet.Add(type);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
            }
        }

        public static bool Validate(Type type)
        {
            var result = false;

            if (type != null)
            {
                if (type.IsGenericType)
                {
                    var gtype = type.GetGenericTypeDefinition();
                    result = _serializeTypeSet.Contains(gtype);
                }
                else if (type.IsArray)
                {
                    var etype = type.GetElementType();
                    result = _serializeTypeSet.Contains(etype);
                }
                else
                {
                    result = _serializeTypeSet.Contains(type);
                }
            }

            return result;
        }
    }
}
